<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="是否逻辑删除" prop="isdelete">
        <el-input v-model="queryParams.isdelete" placeholder="请输入是否逻辑删除" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="数据状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择数据状态" clearable>
          <el-option
            v-for="dict in dict.type.task_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作类型" prop="opType">
        <el-select v-model="queryParams.opType" placeholder="请选择操作类型" clearable>
          <el-option
            v-for="dict in dict.type.task_op_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="模板id" prop="templateId">
        <el-input v-model="queryParams.templateId" placeholder="请输入模板id" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="系统" prop="system">
        <el-input v-model="queryParams.system" placeholder="请输入系统" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['importExport:task:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['importExport:task:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['importExport:task:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['importExport:task:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download" size="mini" @click="handleZxImport"
          >执行导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-upload2" size="mini" @click="handleZxExport"
          >执行导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板id" align="center" prop="templateId" />
      <el-table-column label="操作类型" align="center" prop="opType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_op_type" :value="scope.row.opType"/>
        </template>
      </el-table-column>
      <el-table-column label="文件路径+名称" show-overflow-tooltip align="center" prop="opFileName" />
      <el-table-column label="备注" show-overflow-tooltip align="center" prop="remark" />
      <el-table-column label="创建人" show-overflow-tooltip align="center" prop="createBy" />
      <el-table-column label="创建时间" show-overflow-tooltip align="center" prop="createTime" />
      <el-table-column label="系统" align="center" prop="system" />
      <el-table-column label="导出sql语句" show-overflow-tooltip align="center" prop="sqls" />
      <el-table-column label="文件下载名称" align="center" prop="downloadFileName" show-overflow-tooltip/>
      <el-table-column label="异常消息" align="center" prop="opError" width="200"/>
      <el-table-column label="数据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="执行时间" align="center" prop="executeTime" />
      <el-table-column label="进度" align="center" prop="progress" />
      <el-table-column label="操作"  width="200" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" type="warning"
            @click="handleRestartTaskById(scope.row)">重新运行</el-button>
          <el-button size="small" v-if="scope.row.status == '2' && scope.row.opType == 'export'" type="info"
            @click="handleDownlodaFileById(scope.row)"">下载文件</el-button>
          <el-button size="small" v-if="scope.row.status == '1'" type="danger"
            @click="handleStopTaskById(scope.row)"">停止任务</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['importExport:task:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['importExport:task:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改导入导出任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板id" prop="templateId">
          <el-input v-model="form.templateId" placeholder="请输入模板id" />
        </el-form-item>
        <el-form-item label="数据状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择数据状态">
            <el-option
              v-for="dict in dict.type.task_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作类型" prop="opType">
          <el-select v-model="form.opType" placeholder="请选择操作类型">
            <el-option
              v-for="dict in dict.type.task_op_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件路径+名称" prop="opFileName">
          <el-input v-model="form.opFileName" placeholder="请输入操作文件路径+名称" />
        </el-form-item>
        <el-form-item label="文件下载路径" prop="opDownPath">
          <el-input v-model="form.opDownPath" placeholder="请输入文件下载路径" />
        </el-form-item>
        <el-form-item label="是否异步执行" prop="opAsync">
          <el-select v-model="form.opAsync" placeholder="请选择是否异步执行">
            <el-option
              v-for="dict in dict.type.task_op_async"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作异常消息" prop="opError">
          <el-input v-model="form.opError" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="进度" prop="progress">
          <el-input v-model="form.progress" placeholder="请输入进度" />
        </el-form-item>
        <el-form-item label="执行时间" prop="executeTime">
          <el-input type="number" v-model="form.executeTime" placeholder="请输入执行时间" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="系统" prop="system">
          <el-input v-model="form.system" placeholder="请输入系统" />
        </el-form-item>
        <el-form-item label="导出sql语句" prop="sqls">
          <el-input v-model="form.sqls" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="参数" prop="parameters">
          <el-input v-model="form.parameters" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="文件下载名称" prop="downloadFileName">
          <el-input v-model="form.downloadFileName" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 执行导出任务对话框 -->
    <el-dialog :title="title" :visible.sync="openExport" width="500px" append-to-body>
      <el-form ref="importExportForm" :model="importExportForm" :rules="rules" label-width="80px">
        <el-form-item label="模板" prop="templateId">
          <el-select v-model="importExportForm.templateId" filterable placeholder="请选择模板">
            <el-option
              v-for="item in templates"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="导出sql语句" prop="sqls">
          <el-input v-model="importExportForm.sql" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="文件下载名称" prop="downloadFileName">
          <el-input v-model="importExportForm.downloadFileName" placeholder="请输入文件下载名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImportExportForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 执行导入任务对话框 -->
    <el-dialog :title="title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-form ref="importExportForm" :model="importExportForm" :rules="rules" label-width="80px">
        <el-form-item label="数据源" prop="datasourceId">
          <el-select v-model="importExportForm.datasourceId" @change="selectTable(importExportForm.datasourceId)" filterable placeholder="请选择数据源">
            <el-option
              v-for="item in datasources"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表名" prop="tableName">
          <el-select v-model="importExportForm.tableName" filterable placeholder="请选择表名">
            <el-option
              v-for="item in tables"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?datasourceId=' + importExportForm.datasourceId + '&tableName=' + importExportForm.tableName"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImportExportForm">确 定</el-button>
        <el-button @click="handleCanle">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    listTask,
    getTask,
    delTask,
    addTask,
    updateTask,
    downlodaFileById,
    exportByTempleId,
    restartTaskById,
    stopTaskById,
    importByFile,
    listDatasource,
    listTemplate,
    listTables
  } from "@/api/importExport/task";
  import { downloadFile } from '@/utils/request'
  import { getToken } from "@/utils/auth";

  export default {
    name: "Task",
    dicts: ['task_status', 'task_op_type'],
    data() {
      return {
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/importExport/template/importByFile"
        },
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 导入导出任务表格数据
        taskList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 导入导出弹出层
        openExport: false,
        openImport: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          isdelete: null,
          templateId: null,
          status: null,
          opType: null,
          opFileName: null,
          opDownPath: null,
          opAsync: null,
          opFileType: null,
          opError: null,
          progress: null,
          executeTime: null,
          system: null,
          sqls: null,
          parameters: null
        },
        // 表单参数
        form: {},
        // 数据源列表
        datasources: [],
        // 模板列表
        templates: [],
        // 表
        tables: [],
        //导入导出表单
        importExportForm: {},
        // 表单校验
        rules: {

        }
      };
    },
    created() {
      this.getList();
      this.listDatasource();
      this.listTemplate();
    },
    methods: {
      //根据数据源获取该库的所有表
      selectTable(id){
        listTables(id).then(response => {
          this.tables = response.data;
        });
      },
      /** 查询模板列表 */
      listTemplate() {
        listTemplate().then(response => {
          this.templates = response.data;
        });
      },
      /** 查询数据源列表 */
      listDatasource() {
        listDatasource().then(response => {
          this.datasources = response.data;
        });
      },
      //取消导入
      handleCanle(){
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.resetImportExport();
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.getList();
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      //停止任务 根据任务id
      handleStopTaskById(row){
        this.$modal.confirm('是否停止该任务？').then(function() {
          stopTaskById(row.id).then(response => {
            if(response.code == 200){
              this.$modal.msgSuccess(response.msg);
            }else{
              this.$modal.msgError(response.msg);
            }
          })
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("重新运行成功");
        }).catch(() => {});
      },
      //重新开始任务 根据任务id
      handleRestartTaskById(row){
        this.$modal.confirm('是否重新运行该任务？').then(function() {
          restartTaskById(row.id).then(response => {
            if(response.code == 200){
              this.$modal.msgSuccess(response.msg);
            }else{
              this.$modal.msgError(response.msg);
            }
          })
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("重新运行成功");
        }).catch(() => {});
      },
      //执行导入
      handleZxImport(){
        this.upload.open = true;
        this.title = "输入导入任务参数";
        this.importExportForm.type = "import";
        this.listDatasource();
      },
      //执行导出
      handleZxExport(){
        this.openExport = true;
        this.title = "输入导出任务参数";
        this.importExportForm.type = "export";
        this.listTemplate();
      },
      /** 根据任务id 下载已完成好的文件 */
      handleDownlodaFileById(row){
        var fileName = row.opFileName
        if(fileName == undefined || fileName == ''){
          this.$modal.msgError("未获取到下载地址");
          return
        }
        var downloadFileName = row.downloadFileName
        if(downloadFileName != ''){
          fileName = downloadFileName + fileName.substring(fileName.lastIndexOf('.'))
        }else{
          fileName = fileName.substring(fileName.lastIndexOf('/') + 1)
        }
        this.download('importExport/task/downlodaFileById?id='+row.id+'&fileName=' + fileName,{},fileName)
      },
      /** 查询导入导出任务列表 */
      getList() {
        this.loading = true;
        listTask(this.queryParams).then(response => {
          this.taskList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
        this.openExport = false;
        this.resetImportExport();
      },
      resetImportExport(){
        this.importExportForm = {}
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          isdelete: null,
          templateId: null,
          status: "0",
          opType: null,
          opFileName: null,
          opDownPath: null,
          opAsync: null,
          opFileType: null,
          opError: null,
          progress: null,
          executeTime: null,
          remark: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          system: null,
          sqls: null,
          parameters: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加导入导出任务";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getTask(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改导入导出任务";
        });
      },
      //提交
      submitImportExportForm(){
        let datasourceId = this.importExportForm.datasourceId;
        let tableName = this.importExportForm.tableName;
        let sql = this.importExportForm.sql;
        var type = this.importExportForm.type;
        if(type == "import"){
          if(datasourceId == undefined || datasourceId == ''){
            this.$modal.msgError("数据源不能为空");
            return
          }
          if(tableName == undefined || tableName == ''){
            this.$modal.msgError("表名不能为空");
            return
          }
          var fileList = this.$refs.upload.uploadFiles
          if(fileList.length <= 0){
            this.$modal.msgError("请先上传导入文件");
            return;
          }
          this.$refs.upload.submit().then(response => {
            if(response.code == 200){
              this.upload.open = false;
              this.getList();
              this.$modal.msgSuccess("操作成功，任务id：" + response.msg);
            }else{
              this.$modal.msgError(response.msg);
            }
          })
        }else if(type == "export"){
          if(sql == undefined || sql == ''){
            this.$modal.msgError("导出sql语句不能为空");
            return
          }
          exportByTempleId(this.importExportForm).then(response => {
            if(response.code == 200){
              this.openExport = false;
              this.getList();
              this.$modal.msgSuccess("操作成功，任务id：" + response.msg);
            }else{
              this.$modal.msgError(response.msg);
            }
          })
        }
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateTask(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addTask(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除导入导出任务编号为"' + ids + '"的数据项？').then(function() {
          return delTask(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('importExport/task/export', {
          ...this.queryParams
        }, `task_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
